package user;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jackup.jasp.Activity_Login;
import com.jackup.jasp.R;

import org.xutils.x;

import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;

import Utils.RGB2Int;
import Utils.Waitting_dialog;
import base.Constant;
import user.bean.Company_info_bean;
import user.internet.CurrentPeople_utlis;
import user.internet.GetCompanyInfo_utils;
import user.internet.Logout_utlis;
import user.internet.Scan_utils;

public class Activity_Userpage extends AppCompatActivity implements View.OnClickListener {
    private TextView logout;//退出登录
    private EditText codeinput_edt;//条形码输入框
    private TextView current_num_tv;//当前人数
    private RelativeLayout verify_layout;//验证成功弹出的布局
    private ImageView user_page_content_img;//banner图
    private ImageView circle;//打钩背景圆圈
    private ImageView isVerified_img;//打钩或者打叉
    private TextView isVerified_tv;//提示
    private Vibrator vibrator;//失败震动
    private Dialog dialog;

    private Timer timer = new Timer();
    private TimerTask timerTask;
    private Timer edit_timer = new Timer();
    private TimerTask edit_timertask;
    private GetCompanyInfo_utils companyInfo;//查询当前公司信息
    private CurrentPeople_utlis current;//用于查找当前人数
    private Scan_utils scan_utils;//扫描方法


    private static final String TAG = "Activity_Userpage";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            this.obtainMessage();
            switch (msg.what) {
                case 0://扫码成功
                    if ((boolean) msg.obj == true) {
                        isVerified_tv.setText("验证成功");
                        isVerified_img.setImageResource(R.mipmap.checked);
                        verify_layout.setVisibility(View.VISIBLE);
                        afterVerify(true);
                        current.CurrentPeople(handler);
                    }
                    break;
                case 1://扫码失败
                    long[] pattern = {100, 1000, 100};   // 停止 开启 停止 开启
                    vibrator.vibrate(pattern, -1);           //重复两次上面的pattern 如果只想震动一次，index设-1
//                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//                    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
//                    r.play();
                    wrong_notify();
                    isVerified_tv.setText("验证失败");
                    isVerified_img.setImageResource(R.mipmap.unchecked);
                    verify_layout.setVisibility(View.VISIBLE);
                    afterVerify(false);

                    current.CurrentPeople(handler);
                    break;
                case 2://获取当天人数成功
                    Waitting_dialog.closeDialog(dialog);
                    current_num_tv.setText(msg.obj.toString());
                    break;
                case 3://退出成功
                    Log.e(TAG, "handleMessage: " + "logout");
                    if ((boolean) msg.obj == true) {
                        Intent i = new Intent(Activity_Userpage.this, Activity_Login.class);
                        startActivity(i);
                        Activity_Userpage.this.finish();
                    }
                    break;
                case 4://验证成功图片消失
                    verify_layout.setVisibility(View.INVISIBLE);
                    codeinput_edt.setText("");
                    break;
                case 5://获取公司信息，图片url，颜色
                    Company_info_bean company_info_bean = (Company_info_bean) msg.obj;
                    String url = company_info_bean.getBanner();
                    url = url.substring(1, url.length());
                    x.image().bind(user_page_content_img, Constant.BaseUrl + url);
                    GradientDrawable p = (GradientDrawable) circle.getBackground();
                    p.setColor(RGB2Int.RGB2Int(company_info_bean.getColor()));
                    break;
                case -10086:
                    Waitting_dialog.closeDialog(dialog);
                    Toast.makeText(Activity_Userpage.this,"网络错误",Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userpage);
        initView();
        init();
        getData();
        onTextChange();
    }

    private void init() {
        scan_utils = new Scan_utils();
        current = new CurrentPeople_utlis();
        companyInfo = new GetCompanyInfo_utils();
        vibrator = (Vibrator) getSystemService(Activity_Userpage.this.VIBRATOR_SERVICE);
    }

    private void initView() {
        logout = (TextView) findViewById(R.id.logout);
        logout.setOnClickListener(this);
        logout.setVisibility(View.VISIBLE);
        user_page_content_img = (ImageView) findViewById(R.id.user_page_content_img);
        circle = (ImageView) findViewById(R.id.circle);
        current_num_tv = (TextView) findViewById(R.id.current_num_tv);
        codeinput_edt = (EditText) findViewById(R.id.codeinput_edt);
        isVerified_img = (ImageView) findViewById(R.id.isVerified_img);
        isVerified_tv = (TextView) findViewById(R.id.isVerified_tv);


        verify_layout = (RelativeLayout) findViewById(R.id.verify_layout);
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            codeinput_edt.setInputType(InputType.TYPE_NULL);
        } else {
            Activity_Userpage.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setSoftInputShownOnFocus;
                setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setSoftInputShownOnFocus.setAccessible(true);
                setSoftInputShownOnFocus.invoke(codeinput_edt, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void onTextChange() {
        codeinput_edt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                edit_timer.cancel();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(final Editable s) {
                edit_timer = new Timer();
                edit_timertask = new TimerTask() {
                    @Override
                    public void run() {
                        verify(s.toString());
                    }
                };
                edit_timer.schedule(edit_timertask, 800);
            }
        });
    }

    private void getData() {
        dialog = Waitting_dialog.createLoadingDialog(Activity_Userpage.this);
        companyInfo.GetCompanyInfo(handler);
        current.CurrentPeople(handler);
    }

    private void verify(String number) {
        if (!number.isEmpty()) {
            scan_utils.Scan(number, handler);
        }
    }

    private void afterVerify(boolean flag) {
        timerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 4;
                handler.sendMessage(message);
            }
        };
        if (flag) {
            timer.schedule(timerTask, 1000);
        } else {
            timer.schedule(timerTask, 3000);
        }
    }

    private void wrong_notify() {
        MediaPlayer mediaplayer = MediaPlayer.create(Activity_Userpage.this, R.raw.wrong_notify);
        if (mediaplayer.isPlaying()) {
            mediaplayer.reset();
            mediaplayer = MediaPlayer.create(Activity_Userpage.this, R.raw.wrong_notify);
        }
        mediaplayer.start();//开始播放
    }

    private void logout() {
        new Logout_utlis(handler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.logout:
                logout();
                break;
            default:
                break;
        }
    }
}
